package com.example.a001.part06;


import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.a001.R;

import java.text.DecimalFormat;

public class TableLayou01Activity extends AppCompatActivity {
    private EditText inputEditText;
    private String operator = "";
    private double firstNumber = 0;
    private boolean isNewNumber = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_layou01);
        inputEditText = (EditText)findViewById(R.id.inputEditText);
    }

    public void onButtonClick(View view) {
        String buttonText = ((android.widget.Button) view).getText().toString();
        switch (buttonText) {
            case "+":
            case "-":
            case "*":
            case "/":
                operator = buttonText;
                firstNumber = Double.parseDouble(inputEditText.getText().toString());
                isNewNumber = true;
                break;
            case "=":
                double secondNumber = Double.parseDouble(inputEditText.getText().toString());
                double result = 0;
                switch (operator) {
                    case "+":
                        result = firstNumber + secondNumber;
                        break;
                    case "-":
                        result = firstNumber - secondNumber;
                        break;
                    case "*":
                        result = firstNumber * secondNumber;
                        break;
                    case "/":
                        if (secondNumber != 0) {
                            result = firstNumber / secondNumber;
                        } else {
                            inputEditText.setText("Error");
                            return;
                        }
                        break;
                }
                DecimalFormat df = new DecimalFormat("#.########");
                inputEditText.setText(df.format(result));
                isNewNumber = true;
                break;
            default:
                if (isNewNumber) {
                    inputEditText.setText(buttonText);
                    isNewNumber = false;
                } else {
                    inputEditText.append(buttonText);
                }
                break;
        }
    }

}